/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.restaurant.entity.Area;
import org.springblade.modules.restaurant.entity.CustomerSituation;
import org.springblade.modules.restaurant.excel.CustomerSituationExcel;
import org.springblade.modules.restaurant.service.IAreaService;
import org.springblade.modules.restaurant.service.ICustomerSituationService;
import org.springblade.modules.restaurant.vo.CustomerSituationVO;
import org.springblade.modules.restaurant.wrapper.CustomerSituationWrapper;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 客情信息 控制器
 *
 * @author Blade
 * @since 2025-01-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("/restaurant/customersituation")
@Tag(name = "客情信息", description = "客情信息接口")
public class CustomerSituationController extends BladeController {

	private ICustomerSituationService customerSituationService;
	private IAreaService areaService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入customerSituation")
	public R<CustomerSituation> detail(CustomerSituation customerSituation) {
		CustomerSituation detail = customerSituationService.getOne(Condition.getQueryWrapper(customerSituation));
		return R.data(detail);
	}

	/**
	 * 分页 客情信息
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入customerSituation")
	public R<IPage<CustomerSituation>> list(@ParameterObject CustomerSituation customerSituation, @ParameterObject Query query) {
		IPage<CustomerSituation> pages = customerSituationService.page(Condition.getPage(query),
			Condition.getQueryWrapper(customerSituation).orderByDesc("create_time"));
		return R.data(pages);
	}

	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description = "传入customerSituation")
	public R<IPage<CustomerSituationVO>> page(@ParameterObject CustomerSituationVO customerSituation, @ParameterObject Query query) {
		IPage<CustomerSituation> pages = customerSituationService.page(Condition.getPage(query), customizeQueryWrapper(customerSituation));
		return R.data(CustomerSituationWrapper.build().pageVO(pages));
	}

	/**
	 * 新增 客情信息
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description = "传入customerSituation")
	public R save(@Valid @RequestBody CustomerSituation customerSituation) {
		// 查询归属区域
		Area area = areaService.getParentArea(customerSituation.getRoomId());
		if (area != null) {
			customerSituation.setAreaName(area.getAreaName());
			customerSituation.setAreaId(area.getId());
		}
		return R.status(customerSituationService.save(customerSituation));
	}

	/**
	 * 修改 客情信息
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description = "传入customerSituation")
	public R update(@Valid @RequestBody CustomerSituation customerSituation) {
		// 查询归属区域
		Area area = areaService.getParentArea(customerSituation.getRoomId());
		if (area != null) {
			customerSituation.setAreaName(area.getAreaName());
			customerSituation.setAreaId(area.getId());
		}
		return R.status(customerSituationService.updateById(customerSituation));
	}

	/**
	 * 新增或修改 客情信息
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入customerSituation")
	public R submit(@Valid @RequestBody CustomerSituation customerSituation) {
		// 查询归属区域
		Area area = areaService.getParentArea(customerSituation.getRoomId());
		if (area != null) {
			customerSituation.setAreaName(area.getAreaName());
			customerSituation.setAreaId(area.getId());
		}
		return R.status(customerSituationService.saveOrUpdate(customerSituation));
	}


	/**
	 * 删除 客情信息
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(customerSituationService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 导出采购记录
	 */
	@SneakyThrows
	@GetMapping("/export")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出客情记录", description = "传入situationVO")
	public void export(CustomerSituationVO customerSituation, HttpServletResponse response) {
		List<CustomerSituation> commoditySummaryList = customerSituationService.list(customizeQueryWrapper(customerSituation));
		List<CustomerSituationExcel> list = customerSituationService.export(commoditySummaryList);

		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("客情记录", StandardCharsets.UTF_8)
			+ "_" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);

		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), CustomerSituationExcel.class).sheet("客情记录").doWrite(list);
	}

	private LambdaQueryWrapper<CustomerSituation> customizeQueryWrapper(CustomerSituationVO customerSituation) {

		String[] searchTime = customerSituation.getSearchTime();
		DateTime now = DateUtil.date();
		// 获取今天开始时间  yyyy-MM-dd
		String startTime = DateUtil.formatDate(now);
		// 获取当前时间 yyyy-MM-dd
		String endTime = DateUtil.formatDate(now);

		if (searchTime != null && searchTime.length == 2) {
			startTime = searchTime[0];
			endTime = searchTime[1];
		}

		return Wrappers.<CustomerSituation>lambdaQuery()
			.eq(StrUtil.isNotBlank(customerSituation.getTimeSlot()), CustomerSituation::getTimeSlot, customerSituation.getTimeSlot())
			.like(StrUtil.isNotBlank(customerSituation.getGuestName()), CustomerSituation::getGuestName, customerSituation.getGuestName())
			.like(StrUtil.isNotBlank(customerSituation.getContact()), CustomerSituation::getContact, customerSituation.getContact())
			.between(CustomerSituation::getWriteDate, startTime, endTime)
			.orderByDesc(CustomerSituation::getCreateTime);

	}
}
